package com.chery.media.utils

import android.R
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.content.res.Resources
import android.graphics.drawable.Drawable
import com.chery.media.network.model.AppInfoBean

class AppInfoUtils(mContext: Context) {
    private val packageManager: PackageManager
    private val mIconDpi: Int
    private val appInfos = arrayListOf<AppInfoBean>()

    init {
        val activityManager = mContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        packageManager = mContext.packageManager
        mIconDpi = activityManager.launcherLargeIconDensity
    }

    private fun loadAppsInfo() {
        var apps: List<ResolveInfo>? = null
        val filterIntent = Intent(Intent.ACTION_MAIN, null)
        //Intent.CATEGORY_LAUNCHER主要的过滤条件
        filterIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        apps = packageManager.queryIntentActivities(filterIntent, 0)
        for (resolveInfo in apps) {
            val appInfo = AppInfoBean()
            appInfo.packageName = resolveInfo.activityInfo.applicationInfo.packageName
            appInfo.appName = resolveInfo.loadLabel(packageManager).toString()
            appInfo.appIcon = getResIconFormActyInfo(resolveInfo.activityInfo)
            appInfos.add(appInfo)
        }
    }

    private fun getResIconFormActyInfo(info: ActivityInfo): Drawable {
        val resources: Resources? = try {
            packageManager.getResourcesForApplication(
                info.applicationInfo
            )
        } catch (e: PackageManager.NameNotFoundException) {
            null
        }
        if (resources != null) {
            val iconId = info.iconResource
            if (iconId != 0) {
                return getResIconFormActyInfo(resources, iconId)
            }
        }
        return defaultIcon
    }

    private fun getResIconFormActyInfo(resources: Resources, iconId: Int): Drawable {
        val drawable: Drawable? = try {
            resources.getDrawableForDensity(iconId, mIconDpi)
        } catch (e: Resources.NotFoundException) {
            null
        }
        return drawable ?: defaultIcon
    }

    private val defaultIcon: Drawable
        //获取一个默认的图标，避免为空的情况
        private get() = getResIconFormActyInfo(
            Resources.getSystem(),
            R.mipmap.sym_def_app_icon
        )
    val appList: ArrayList<AppInfoBean>
        //外部获取信息的方法
        get() {
            loadAppsInfo()
            return appInfos
        }
}